<template>
  <div class="mental-statistics">
    <h2>{{ this.selectedSchool }}</h2>
    <!-- 图形图表区 -->
    <div v-if="this.index == 1">
      <div class="bread-crumbs">
        <div class="bread">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <!--        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>-->
            <el-breadcrumb-item>{{ this.selectedSchool }}</el-breadcrumb-item>
            <el-breadcrumb-item>心理统计图形统计</el-breadcrumb-item>
            <!--        <el-breadcrumb-item>活动详情</el-breadcrumb-item>-->
          </el-breadcrumb>
        </div>
        <div class="view_switch">
          <button @click="clickIndex(index)"><span class="el-icon-sort">列表统计</span></button>
        </div>
      </div>
      <div class="heart_search1">
        <span style="padding-right: 20px;">起止日期</span>
        <el-date-picker
          v-model="dateArr" clearable end-placeholder="结束日期"
          range-separator="至" start-placeholder="开始日期"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="mini">
        </el-date-picker>
        <!-- 选择学校 -->
        <!-- <el-select
         v-model="selectedSchool"
         clearable
         filterable
         placeholder="请选择学校"
         :loading="schoolLoading"
         @change="schoolInput"
         :disabled="canSelect"
       >
         <el-option
           v-for="(item, i) in schools"
           :key="i"
           :value="item.enterpriseName"
           :label="item.enterpriseName"
         ></el-option>
       </el-select> -->
        <!-- 选择年级 -->
        <span>年级</span>
        <el-select size="mini" v-if="consumeType !== 2" v-model="selectedGrade" :loading="gradeLoading" clearable
                   filterable placeholder="请选择年级" style="margin: 0 20px;" @change="gradeInput">
          <el-option v-for="(item, i) in grades" :key="i" :label="item.grade" :value="item.grade"></el-option>
        </el-select>
        <!-- 选择班级 -->
        <span>班级</span>
        <el-select size="mini" v-if="consumeType !== 2" v-model="selectedClass" :loading="classLoading" clearable
                   filterable placeholder="请选择班级" @change="classInput">
          <el-option v-for="(item, i) in classes" :key="i" :label="item.grades" :value="item.grades"></el-option>
        </el-select>
        <!-- 查询 -->
        <div>
          <el-button size="mini" :loading="isSearching" type="success" @click="beginSearch">
            <i class="el-icon-search">查询</i>
          </el-button>
        </div>

      </div>
      <div>
        <div class="heart_block1">
<!--          只有第一个块块不在left div中-->
          <div class="block1_pic">
            <p class="bad_num1 ">学校总人数</p>
            <p class="big_badNum1">{{ totalNum }}</p>
            <p class="personIn">参与人数占比 {{ joinPerson() }}%</p>
            <el-progress :percentage="joinPerson()" :show-text="false"></el-progress>
          </div>
          <div class="block1_pic" style="width: 360px">
            <div class="left">
              <p class="bad_num">心理测评次数</p>
              <p class="big_badNum">{{ mentalTestNum }}</p>
            </div>
            <div class="right">
              <img height="82" src="../assets/images/hearttest.png" width="87"/>
            </div>
          </div>
          <div class="block1_pic" style="width: 350px">
            <div class="left">
              <p class="bad_num">心理测评人数</p>
              <p class="big_badNum">{{ mentalPeopleNum }}</p>
            </div>
            <div class="right">
              <el-progress :percentage="joinPerson()" :width="80" type="circle"></el-progress>
            </div>
          </div>
          <div class="block1_pic" style="width: 484px;display: flex">
            <div class="left" style="flex: 1">
              <p class="bad_num">异常人数</p>
              <p class="big_badNum">{{ badNum }}</p>
            </div>
            <div style="flex: 1;margin-top: 25px;line-height: 121px">
              <el-progress :percentage="badPerson()" :width="80" type="circle"></el-progress>
            </div>
            <div style="flex: 1;text-align: center;">
              <p class="beginSearchNumber" @click="lookFirm" :loading="searchLoading">查看参与人数</p>
            </div>
          </div>

        </div>
        <div id="heart_block2" ref="chartLine"></div>
        <div class="heart_block3">
          <div class="block3_pic1" ref="agePieWrap">
            <div v-if="hasAge" ref="agePie" :style="{'width': agePieWidth + 'px', 'height': '300px'}"></div>
          </div>
          <div class="block3_pic2" ref="genderPieWrap">
            <div v-if="hasGender" ref="genderPie" :style="{'width': genderPieWidth + 'px', 'height': '300px'}"></div>
          </div>
          <div class="block3_pic3" ref="ruleBarWrap">
            <div v-if="hasRule" ref="ruleBar" :style="{'width': ruleBarWidth + 'px', 'height': '300px'}"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 列表区 -->
    <div v-if="this.index == 2">
      <div class="bread-crumbs">
        <div class="bread">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <!--        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>-->
            <el-breadcrumb-item>{{ this.selectedSchool }}</el-breadcrumb-item>
            <el-breadcrumb-item>心理统计表单统计</el-breadcrumb-item>
            <!--        <el-breadcrumb-item>活动详情</el-breadcrumb-item>-->
          </el-breadcrumb>
        </div>
        <div class="view_switch">
          <button @click="clickIndex(index)"><span class="el-icon-sort">图形统计</span></button>
        </div>
      </div>
      <div class="heart_search1">
        <span style="padding-right: 20px;">起止日期</span>
        <el-date-picker
          v-model="dateArr"
          clearable
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="mini"
        ></el-date-picker>
        <!-- 查询 -->
        <div>
          <el-button size="mini" :loading="isSearching" type="success" @click="beginSearch">
            <i class="el-icon-search">查询</i>
          </el-button>
        </div>
      </div>
      <div class="choose_content">
        <!--选择类型-->
        <div class="choose_person">
          <span class="choose_text"> 类型： </span>
          <div class="person_button">
            <!-- 暂时留着-->
            <el-radio-group v-model="resultType" @change="changeResultType" size="medium">
              <el-radio-button label="正常名单"></el-radio-button>
              <el-radio-button label="异常名单"></el-radio-button>
            </el-radio-group>
            <el-radio-group v-model="unitType" @change="changeUnitType" size="medium">
              <el-radio-button label="按学校统计"></el-radio-button>
              <el-radio-button label="按年级统计"></el-radio-button>
              <el-radio-button label="按班级统计"></el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <!--年级-->
        <div class="choose_grade">
          <span class="choose_text"> 年级： </span>
          <div class="grade_button">
            <el-radio-group v-model="selectedGrade" size="small" @change="gradeInput">
              <el-radio-button
                :label="item.grade"
                v-for="(item, i) in grades"
                :key="i" :value="item.grade"
              >{{ item.grade }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <!--班级-->
        <div class="choose_class">
          <span class="choose_text"> 班级： </span>
          <!-- <el-select
            size="mini"
            v-if="consumeType !== 2"
            v-model="selectedClass"
            :loading="classLoading"
            clearable
            filterable
            placeholder="请选择班级"
            @change="classInput"
          >
            <el-option
              v-for="(item, i) in classes"
              :key="i"
              :label="item.grades"
              :value="item.grades"
            ></el-option>
          </el-select>-->
          <div class="class_button">
            <el-radio-group v-model="selectedClass" @change="classInput" size="small">
              <el-radio-button
                v-for="(item, i) in classes"
                :key="i"
                :label="item.grades"
                :value="item.grades"
                :loading="classLoading"
              >{{ item.grades }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <!--表类型-->
        <div class="choose_test">
          <span class="choose_text"> </span>
          <div class="test_button">

            <el-radio-group
              v-model="selectChartIndex"
              @change="changeChart"
              size="small">
              <el-radio-button
                v-for="(item, index) in chartNameList"
                :key="index"
                :label="item"
              >{{ item }}
              </el-radio-button>

            </el-radio-group>
          </div>
        </div>
      </div>
      <div class="table_list">
        <el-table :data="targetList" v-loading="computing" class="m-t-b">
          <!--        <el-table-column label="序号" prop="order"></el-table-column>-->
          <!--        <el-table-column label="年级" prop="gradeName"></el-table-column>-->
          <!--        <el-table-column label="班级" prop="className"></el-table-column>-->
          <el-table-column label="学号" prop="snoNum"></el-table-column>
          <el-table-column label="昵称/名称" prop="nickname"></el-table-column>
          <el-table-column label="性别" prop="gender"></el-table-column>
          <el-table-column label="年龄" prop="age"></el-table-column>
          <el-table-column label="所测量表" prop="chartName"></el-table-column>
          <el-table-column label="测评时间" prop="testTime"></el-table-column>
          <template v-for="(item, index) in ruleTitleList">
            <el-table-column :label="item + '程度'" :prop="'ruleLevel$' + index" :key="index + 'a'"></el-table-column>
            <el-table-column :label="item + '分数'" :prop="'ruleScore$' + index" :key="index + 'b'"></el-table-column>
          </template>
          <!--        <el-table-column label="异常规则数" prop="badRuleNum"></el-table-column>-->
          <el-table-column label="规则总分" prop="totalScore"></el-table-column>
          <el-table-column label="家长微信昵称" prop="parentName"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button class="el-icon-document table_button" @click="goExportResult(scope.row)"
                         size="mini"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>

    <!--<el-tabs v-if="this.index == 3" type="border-card" class="m-t-b">
            <el-tab-pane label="表格展示" name="table">
              <div class="filter-wrap">
                <el-radio-group v-model="unitType" @change="changeUnitType">
                  <el-radio-button label="按学校统计"></el-radio-button>
                  <el-radio-button label="按年级统计"></el-radio-button>
                  <el-radio-button label="按班级统计"></el-radio-button>
                </el-radio-group>

                <el-radio-group v-model="resultType" @change="changeResultType">
                  <el-radio-button label="正常名单"></el-radio-button>
                  <el-radio-button label="异常名单"></el-radio-button>
                </el-radio-group>
              </div>

              <div class="chart-body m-t-b">
                <ul class="chart-class">
                  <li
                    v-for="(item, index) in groupNameList"
                    :key="index"
                    :class="classSelectIndex === index ? 'active' : ''"
                    @click="changeClass(index)"
                  >{{ item }}
                  </li>
                </ul>
                <div class="m-t-b" style="display: flex; justify-content: space-between; padding: 0 10px;">
                  表单
                  <el-radio-group
                    v-model="selectChartIndex"
                    @change="changeChart"
                  >
                    <el-radio-button
                      v-for="(item, index) in chartNameList"
                      :key="index"
                      :label="item"
                    ></el-radio-button>
                  </el-radio-group>
                  <el-button
                    type="primary"
                    @click="exportNameList"
                    v-if="targetList.length"
                  >导出名单
                  </el-button>

                </div>
                <el-table :data="targetList" v-loading="computing" class="m-t-b">
                  <el-table-column label="序号" prop="order"></el-table-column>
                  <el-table-column label="年级" prop="gradeName"></el-table-column>
                  <el-table-column label="班级" prop="className"></el-table-column>
                  <el-table-column label="学号" prop="snoNum"></el-table-column>
                  <el-table-column label="成员昵称" prop="nickname"></el-table-column>
                  <el-table-column label="年龄" prop="age"></el-table-column>
                  <el-table-column label="性别" prop="gender"></el-table-column>
                  <el-table-column label="家长微信昵称" prop="parentName"></el-table-column>
                  <el-table-column label="测评时间" prop="testTime"></el-table-column>
                  <el-table-column label="量表名称" prop="chartName"></el-table-column>
                  <el-table-column label="异常规则数" prop="badRuleNum"></el-table-column>
                  <template
                    v-for="(item, index) in ruleTitleList"
                  >
                    <el-table-column
                      :label="item + '程度'"
                      :prop="'ruleLevel$' + index"
                      :key="index + 'a'"
                    ></el-table-column>
                    <el-table-column
                      :label="item + '分数'"
                      :prop="'ruleScore$' + index"
                      :key="index + 'b'"
                    ></el-table-column>
                  </template>
                  <el-table-column label="规则总分" prop="totalScore"></el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button
                        type="primary"
                        @click="goExportResult(scope.row)"
                        size="mini"
                      >查看结果报表
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>


            </el-tab-pane>
            <el-tab-pane label="所有成员">
              <div
                class="m-t-b"
                style="font-weight: bold; font-size: 20px;"
              >
                总人数: {{ memberTotal }}人
              </div>
              <el-table :data="memberList" stripe border v-loading="memberLoading" class="m-t-b">
                <el-table-column label="昵称" prop="name"></el-table-column>
                <el-table-column label="性别">
                  <template slot-scope="scope">
                    {{ scope.row.sex == 1 ? '男' : '女' }}
                  </template>
                </el-table-column>
                <el-table-column label="年龄" prop="barthday"></el-table-column>
                <el-table-column label="年级" v-if="consumeType == 1">
                  <template slot-scope="scope">
                    {{ `${scope.row.grade} - ${scope.row.grades} - ${scope.row.sno}` }}
                  </template>
                </el-table-column>
                <el-table-column label="家长微信昵称" prop="nickname"></el-table-column>
                <el-table-column label="创建时间" prop="createDate"></el-table-column>
              </el-table>
              <el-pagination
                class="flex m-t-b"
                :page-size="pageSize"
                layout="prev, pager, next"
                @current-change="handlePagi"
                :total="memberTotal">
              </el-pagination>
            </el-tab-pane>

            <el-tab-pane label="参与人数统计">
              <el-button
                v-if="selectedSchool"
                type="primary"
                @click="beginSearchNumber"
                :loading="searchLoading"
              >统计人数
              </el-button>
              <div>
                <div
                  class="grade-data"
                  :style="{width: (gradeNumList.length + 1) * 100 + gradeNumList.length + 1 + 'px'}"
                  v-if="gradeNumList.length"
                >
                  <div class="s-name">
                    {{ selectedSchool }}班级数据分布情况
                  </div>
                  <div style="display: flex;">
                    <div class="class-name">
                      <span></span>
                      <span
                        v-for="num in classMaxNum"
                        :key="num"
                        style="background-color: #E2EFDA; font-size: 18px; font-weight: bold;"
                      >{{ num + '班' }}</span>
                      <span style="background-color: #E2EFDA; font-size: 18px; font-weight: bold;">未知班级</span>
                      <span style="background-color: #E2EFDA; font-size: 18px; font-weight: bold;">总数</span>
                      <span style="background-color: #E2EFDA; font-size: 18px; font-weight: bold;">合计</span>
                    </div>
                    <div class="grade-list">
                      <div>
                        <div
                          v-for="(item, index) in gradeNumList"
                          :key="index"
                        >
                                  <span
                                    style="background-color: #E2EFDA; font-size: 18px; font-weight: bold;">{{ item.gradeName }}</span>
                          <span
                            v-for="num in classMaxNum"
                            :key="num"
                            :style="{color: item[num + '班'] ? '#242424' : 'red'}"
                          >
                                    {{ item[num + '班'] ? item[num + '班'].length : '未参与' }}
                                  </span>
                          <span
                            :style="{color: item['未知班级'] ? '#242424' : 'red'}"
                          >{{ item['未知班级'] ? item['未知班级'].length : '未参与' }}</span>
                          <span>{{ item.total }}</span>
                        </div>
                      </div>
                      <div
                        style="height: 40px; justify-content: center; align-items: center; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc"
                      >
                        {{ memberTotalNum }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>

          </el-tabs>-->

    <!-- 查看参与人数-->
    <div v-if="this.index == 3">
      <div class="bread-crumbs">
        <div class="bread">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <!--        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>-->
            <el-breadcrumb-item>{{ this.selectedSchool }}</el-breadcrumb-item>
            <el-breadcrumb-item>心理统计参与人数统计</el-breadcrumb-item>
            <!--        <el-breadcrumb-item>活动详情</el-breadcrumb-item>-->
          </el-breadcrumb>
        </div>
        <div class="view_switch">
          <button @click="clickIndex(index)"><span class="el-icon-sort">图形统计</span></button>
        </div>
      </div>

      <el-tabs v-if="this.index == 3" type="border-card" class="m-t-b">
        <el-tab-pane label="参与人数统计">
          <div>
            <div
              class="grade-data"
              :style="{width: (gradeNumList.length + 1) * 100 + gradeNumList.length + 1 + 'px'}"
              v-if="gradeNumList.length">

              <div class="s-name">
                {{ selectedSchool }}班级数据分布情况
              </div>

              <div style="display: flex;">

                <div class="class-name">
                  <!--遍历班级-->
                  <span></span>
                  <span v-for="num in classMaxNum" :key="num" style="background-color: #F0F0F0; font-size: 18px; font-weight: bold;">
                    {{ num + '班' }}
                  </span>
                  <span style="background-color: #F0F0F0; font-size: 18px; font-weight: bold;">未知班级</span>
                  <span style="background-color: #F0F0F0; font-size: 18px; font-weight: bold;">总数</span>
                  <span style="background-color: #F0F0F0; font-size: 18px; font-weight: bold;">合计</span>
                </div>

                <div class="grade-list">
                  <div>
                    <div v-for="(item, index) in gradeNumList" :key="index">
                      <span style="background-color: #FDFDFD; font-size: 18px; font-weight: bold;">
                        {{ item.gradeName }}
                      </span>
                      <span
                        v-for="num in classMaxNum"
                        :key="num"
                        :style="{color: item[num + '班'] ? '#242424' : 'red'}">
                        {{ item[num + '班'] ? item[num + '班'].length : '未参与' }}
                      </span>
                      <span :style="{color: item['未知班级'] ? '#242424' : 'red'}">
                        {{ item['未知班级'] ? item['未知班级'].length : '未参与' }}
                      </span>
                      <span>{{ item.total }}</span>
                    </div>
                  </div>

                  <div
                    style="height: 40px; justify-content: center; align-items: center; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc">
                    {{ memberTotalNum }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

    </div>

  </div>

</template>

<script>
import * as echarts from 'echarts';
import json2Excel from "../util/json2Excel";
import {
  mentalStatistics,
  getMentalBadNum,
  getMentalSchool,
  getMentalGrade,
  getMentalNameList,
  getMentalClass
} from "../api";
import {
  getSchoolInfo,
  getSchoolMember,
  getMemberBySchool,
  getProvinceInfo,
  getCityInfo,
  getSchoolInfoCity,
  getMentalSummary
} from '../api/version2';
import {
  mapStr2Json,
  formatDate,
  removeSame
} from "../util/index";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

export default {
  name: "MentalStatistics",
  data() {
    const echarts = this.$echarts;
    return {
      index: 1,
      activeName: '',
      isShow: false, //正常表格异常规则默认不显示
      totalNum: '--', // 统计总人数
      mentalTestNum: '--', // 心理测评次数
      mentalPeopleNum: '--', // 心理测评人数
      badNum: '--', // 异常次数
      hasChart: true,
      hasGender: true,
      resultType: '正常名单',
      StatisticsType: '根据班级统计',
      hasAge: true,
      hasRule: true,
      isRequesting: false,
      eLoading: false,
      computing: false,
      // 省份
      selectedProvince: "",
      provinces: [],
      provinceLoading: false,
      // 城市
      selectedCity: "",
      cities: [],
      cityLoading: false,
      // 学校
      selectedSchool: "",
      selectedGrade: "",
      selectedClass: "",
      schoolLoading: false,
      gradeLoading: false,
      classLoading: false,
      memberLoading: false,
      pageSize: 10,
      memberTotal: 0,
      consumeType: 1, // 统计类型 1: 学校 2: 公司 3: 医院
      memberList: [],
      dateArr: ["", ""],
      tableList: [],
      schools: [],
      grades: [],
      createDate: "",
      flag: false,
      type: 1,
      classes: [],
      peopleNum: "",
      canSelect: false,
      isSearching: false,
      ageRate: [], // 年龄比例
      psychologyNumber: 0, // 学校进行过心理测评的人数
      resultRate: [], // 结果比例
      ruleRate: [], // 规则比例
      studentNumber: 0, // 学校人数
      genderRate: [], // 性别比例
      chartLineWidth: "",
      genderPieWidth: '',
      agePieWidth: '',
      ruleBarWidth: '',
      groupNameList: [],
      genderData: {
        labels: ["男生", "女生"],
        datasets: [
          {
            name: "性别分布",
            type: "pie",
            data: [
              {value: 23, name: "女生"},
              {value: 67, name: "男生"}
            ],
            // roseType: 'radius',
            label: {
              color: "rgba(0, 0, 0, 1)"
            }
          }
        ]
      }, // 性别分布饼图数据
      ageData: {
        labels: ["3岁", "6岁", "12岁", "15岁", "18岁"],
        datasets: [
          {
            data: [23, 43, 45, 32, 12],
            type: "bar",
            showBackground: true,
            backgroundStyle: {
              color: "rgba(220, 220, 220, 0.8)"
            }
          }
        ]
      },
      chartLineChart: null, // 心理表测试情况分布图
      genderPie: null, // 性别分布图
      agePie: null, // 年龄分布图
      ruleBar: null, // 规则分布图
      mentalChartData: null, // 心理分布图数据
      goodList: [],
      badList: [],
      badNameList: [],
      gradeList: [
        '幼儿园', '一年级', '二年级', '三年级', '四年级', '五年级', '六年级', '初中一年级', '初中二年级', '初中三年级', '高中一年级', '高中二年级', '高中三年级'
      ],
      isLoading: false,
      isGoing: false,
      testChartData: '', // 心理测试分布图标数据
      genderChartData: '', // 性别分布图标数据
      ageChartData: '', // 年龄分布图标数据
      ruleChartData: '', // 规则分布图标数据
      allNameList: [],
      goodNameList: [],
      searchLoading: false,
      classMaxNum: 10,
      gradeNumList: [],
      memberTotalNum: 0,
      chartNameList: [],

      classSelectIndex: 0,
      chartDataObj: {},
      selectChartIndex: 0,
      targetList: [],
      ruleTitleList: [],
      unitType: '按班级统计',
      gradeMap: {
        '一年级': 1,
        '二年级': 2,
        '三年级': 3,
        '四年级': 4,
        '五年级': 5,
        '六年级': 6,
        '初一': 7,
        '初二': 8,
        '初三': 9,
        '高一': 10,
        '高二': 11,
        '高三': 12,
        '未知年级': 99
      }
    };
  },
  components: {
    // PieChart,
    // BarChart
  },
  methods: {
    beginSearch() { // 搜索
      if (!this.selectedSchool) {
        return this.$message.error("请输入有效搜索条件");
      }
      this.badNameList = [];
      this.memberList = [];
      this.fetchMentalStatistics();
      this.fetchBadNum(1);
      this.fetchSchoolMembers(1)
    },
    changeClass(index) { // 切换班级
      if (this.classSelectIndex === index) return;
      (index >= 0) && (this.classSelectIndex = index);
      this.changeChart()
    },
    changeUnitType(e) { // 切换统计类型
      console.log(e)
      this.classSelectIndex = 0;
      this.formatNameData()
    },
    changeChart(e) { // 切换量表
      console.log(e)
      this.computing = true;
      this.selectChartIndex = e;
      const tempList = this.chartDataObj[this.groupNameList[this.classSelectIndex]];
      if (!e) {
        let chartTitleList = tempList.map(item => item.chartName);
        this.chartNameList = Array.from(new Set(chartTitleList));
      }
      ;
      this.selectChartIndex = e || this.chartNameList[0];
      this.targetList = tempList.filter(item => item.chartName === this.selectChartIndex);
      this.targetList.forEach((item, index) => {
        item.order = index + 1
      });
      const nameList = [];
      for (let key in this.targetList[0]) {
        if (key.indexOf('ruleName') !== -1) {
          nameList.push(this.targetList[0][key])
        }
      }
      ;
      this.ruleTitleList = nameList;
      this.computing = false
    },
    exportMentalSummary() { // 导出心理综述
      this.eLoading = true;
      getMentalSummary(this.selectedSchool)
        .then(res => {
          const ossUrl = res.data.data.url;
          const a = document.createElement('a');
          a.href = ossUrl;
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          a.removeChild(a);
          this.eLoading = false
        })
        .catch(e => {
          this.eLoading = false
        })
    },
    handlePagi(page) {
      this.fetchSchoolMembers(page)
    },
    // tabClick({index}) { // tab页标签
    //   if (index == '0' && this.selectedSchool) {
    //     let {labels, data} = this.testChartData;
    //     // 心理测试分布图
    //     this.drawChartLineChart(labels, data[0], data[1], data[2]);
    //     // 性别分布图
    //     this.drawGenderPieChart(this.genderChartData);
    //     // 年龄分布图
    //     this.drawAgePieChart(this.ageChartData);
    //     // 规则分布
    //     this.drawRuleBarChart(this.ruleChartData)
    //   } else if (index == 2) {
    //     console.log('查看成员')
    //   }
    // },
    fetchBadNum(type) { // 查询统计名单 1: 正常 2: 异常
      // 获取异常人数
      this.isGoing = true
      getMentalBadNum({
        type,
        statisticName: this.selectedSchool
      })
        .then(res => {
          console.log("==========")
          console.log(res);
          if (res.data.code == 1) {
            this.allNameList = res.data.data || [];
            this.formatNameData()
          } else {
            this.$message.success(res.data.msg || '服务异常704!');
            this.isGoing = false
          }
        })
        .catch(e => {
          console.warn(e);
          this.isGoing = false
          this.$message.error('无数据（743）!')
        })
    },
    dealBadList(list) { // 处理异常名单数据
      let newList = [];
      for (let i = 0; i < list.length; i++) {
        let cur = newList.find(item => item.orderNum === list[i].orderNum);
        if (cur) {
          cur.psychologicalrulesTitle += ('&' + list[i].psychologicalrulesTitle)
        } else {
          newList.push(list[i])
        }
      }
      ;
      return newList
    },
    // 时间戳转换为标准时间
    timeTransform(str) {
      let day = new Date(str);
      if (day == 'Invalid Date') {
        return 'Invalid Date'
      }
      ;
      let year = day.getFullYear();
      let month = day.getMonth() + 1;
      let date = day.getDate();
      let hour = day.getHours();
      let min = day.getMinutes();
      let second = day.getSeconds();
      let timeStamp = `${year}年${month}月${date}日 ${hour}时${min}分${second}秒`;
      return timeStamp;
    },
    exportNameList() { // 导出名单
      let name = `${this.selectedSchool}-心理测评-${this.resultType}-${this.unitType}`;
      const tempList = [];
      const filterList = [];
      this.ruleTitleList.forEach((item, index) => {
        tempList.push(...[item + '程度', item + '分数']);
        filterList.push('ruleName$' + index)
      });
      filterList.push(...['ruleLength', 'totalScore', 'listId', 'memberId']);
      json2Excel(this.targetList, name, ['序号', '年级', '班级', '学号', '学生昵称', '年龄(岁)', '性别', '家长昵称', '测评时间', '量表名称', '异常规则数', ...tempList], filterList)
    },
    formatNameData() { // 格式化名单数据 1: 学校 2: 年级 3: 班级
      const tempObj = {};
      const _str2Json = str => str ? str.slice(1, str.length - 1).split(',') : [];
      this.allNameList.forEach((item, index) => {
        const gradeName = item.grade || '未知年级';
        const className = item.grades || '未知班级';
        const snoNum = item.sno || '未知学号';
        let groupKey;
        switch (this.unitType) {
          case '按学校统计':
            groupKey = item.schoolName;
            break
          case '按年级统计':
            groupKey = gradeName;
            break
          case '按班级统计':
            groupKey = gradeName + '-' + className;
            break
          default:
            break
        }
        ;

        const ruleInfoObj = {};
        let ruleTitleList = _str2Json(item.psychologicalrulesTitle);
        this.ruleTitleList = ruleTitleList;
        let ruleScoreList = _str2Json(item.totalScore);
        let ruleTypeList = _str2Json(item.degree);
        let badRuleNameNum = item.abnormalQuantity;
        let totalScore = ruleScoreList.reduce((a, b) => Number(a) + Number(b));
        ruleTitleList.forEach((rule, i) => {
          ruleInfoObj['ruleName$' + i] = rule;
          ruleInfoObj['ruleLevel$' + i] = ruleTypeList[i];
          ruleInfoObj['ruleScore$' + i] = ruleScoreList[i]
        });

        const itemBaseObj = {
          order: index + 1, // 序号
          gradeName, // 年级
          className, // 班级
          snoNum, // 学号
          nickname: item.memberNickname, // 成员昵称
          age: item.age, // 年龄
          gender: item.gender == 1 ? '男' : '女', // 性别
          parentName: item.userNickname, // 家长微信昵称
          testTime: this.timeTransform(item.quizTime), // 测评时间
          chartName: item.psychologyTitle, // 量表名称
        };
        const itemObj = {
          ...itemBaseObj,
          badRuleNum: badRuleNameNum,
          ...ruleInfoObj,
          totalScore,
          ruleLength: ruleTitleList.length,
          listId: item.listId,
          memberId: item.memberId
        };
        if (!tempObj[groupKey]) {
          tempObj[groupKey] = [itemObj]
        } else {
          tempObj[groupKey].push(itemObj)
        }
      });
      this.groupNameList = Object.keys(tempObj);
      this.chartDataObj = tempObj;
      this.changeClass(-1)
    },
    changeResultType(e) { // 更改结果类型
      console.log(e)
      if (!this.selectedSchool) return;
      this.tableList = [];
      this.badNameList = [];
      this.goodNameList = [];
      this.fetchBadNum(e === '正常名单' ? 1 : 2)
    },

    // --------------------改-------------------------
    drawChartLineChart(labels, list1, list2, list3) { // 折线图
      let lineChart = this.$echarts.init(this.$refs.chartLine);
      this.chartLineChart = lineChart;
      let option = {
        title: {
          text: "心理测试表测试情况分布"
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          // orient: 'vertical',
          right: "0",
          data: ["回答次数", "回答人数", "异常人数"]
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: labels
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        color: ["#E57E81", "#F7BF7E", "#5DC99D"],

        series: [
          {
            name: "回答人数",
            type: "bar",
            stack: '人',
            emphasis: {
              focus: 'series'
            },
            data: list1,
          },
          {
            name: "回答次数",
            type: "bar",
            stack: '人',
            data: list2,
            emphasis: {
              focus: 'series'
            },
          },
          {
            name: "异常人数",
            type: "bar",
            stack: '人',
            data: list3,
            emphasis: {
              focus: 'series'
            },
          }


        ]

      };
      lineChart.setOption(option);
    },
    // drawGenderPieChart(data) { // 性别分布图
    //   let genderPie = this.$echarts.init(this.$refs.genderPie);
    //   this.genderPie = genderPie;
    //   let option = {
    //     title: {
    //       text: '性别分布'
    //     },
    //     toolbox: {
    //       feature: {
    //         saveAsImage: {}
    //       }
    //     },
    //     tooltip: {
    //       trigger: "item",
    //       formatter: "{a} <br/>{b}: {c} ({d}%)"
    //     },
    //     legend: {
    //       // orient: "vertical",
    //       // left: 10,
    //       data: ["男生", "女生"]
    //     },
    //     series: [
    //       {
    //         name: "性别分布",
    //         type: "pie",
    //         radius: ["50%", "70%"],
    //         avoidLabelOverlap: false,
    //         label: {
    //           show: true,
    //           // position: "inside",
    //           formatter: '{b}: {c}人'
    //         },
    //         emphasis: {
    //           label: {
    //             show: true,
    //             // fontSize: "30",
    //             // fontWeight: "bold"
    //           }
    //         },
    //         labelLine: {
    //           show: false
    //         },
    //         data: data
    //       }
    //     ]
    //   };
    //   genderPie.setOption(option);
    // },

    // drawAgePieChart (data) { // 年龄分布图
    //   let agePie = this.$echarts.init(this.$refs.agePie);
    //   this.agePie = agePie;
    //   let option = {
    //     title: {
    //       text: '年龄分布图'
    //     },
    //     tooltip: {
    //       trigger: 'item',
    //       formatter: '{a} <br/>{b} : {c} ({d}%)'
    //     },
    //     legend: {
    //       show: false,
    //       left: 'center',
    //       top: 30,
    //       data: data.labels
    //     },
    //     toolbox: {
    //       feature: {
    //         saveAsImage: {}
    //       }
    //     },
    //     series: [
    //       {
    //         name: '年龄分布',
    //         type: 'pie',
    //         // radius: [20, 110],
    //         // center: ['25%', '50%'],
    //         roseType: 'radius',
    //         label: {
    //           show: true,
    //           formatter: '{b}: {c}人'
    //         },
    //         emphasis: {
    //           label: {
    //             show: true
    //           }
    //         },
    //         data: data.data
    //       }
    //     ]
    //   };
    //   agePie.setOption(option)
    // },

    // drawRuleBarChart (data) { // 规则分布图
    //   let ruleBar = this.$echarts.init(this.$refs.ruleBar);
    //   this.ruleBar = ruleBar;
    //   let option = {
    //     title: {
    //       text: '规则分布图'
    //     },
    //     dataZoom: [{
    //       type: 'slider',
    //       show: true,
    //       xAxisIndex: [0],
    //       left: '9%',
    //       bottom: -5,
    //       start: 10,
    //       end: 90 //初始化滚动条
    //     }],
    //     tooltip: {
    //       trigger: 'axis',
    //       axisPointer: {
    //         type: 'cross',
    //         label: {
    //           backgroundColor: '#283b56'
    //         }
    //       }
    //     },
    //     toolbox: {
    //       feature: {
    //         saveAsImage: {}
    //       }
    //     },
    //     xAxis: [
    //       {
    //         type: 'category',
    //         data: data.labels
    //       }
    //     ],
    //     yAxis: [
    //       {
    //         type: 'value',
    //         name: '人数'
    //       }
    //     ],
    //     series: [
    //       {
    //         name: '测试人数',
    //         type: 'bar',
    //         data: data.data
    //       },
    //       // {
    //       //   name: '异常人数',
    //       //   type: 'line',
    //       //   data: [3, 40, 54, 65]
    //       // }
    //     ]
    //
    //
    //   };
    //   ruleBar.setOption(option)
    // },
    // 省份输入

    drawGenderPieChart(data) { //性别
      let genderPie = this.$echarts.init(this.$refs.genderPie);
      this.genderPie = genderPie;
      let option;

      option = {
        title: {
          text: '性别分布',
          // subtext: '纯属虚构',
          left: '0'
        },
        tooltip: {
          trigger: 'item'
        },
        color: ["#5DC99D", "#E57E81"],
        legend: {
          orient: 'vertical',
          bottom: 'bottom',
        },
        series: [
          {
            name: '性别',
            type: 'pie',
            radius: '50%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      genderPie.setOption(option);
    },
    drawAgePieChart(data) { //年龄
      let agePie = this.$echarts.init(this.$refs.agePie);
      this.agePie = agePie;
      let option;

      option = {
        title: {
          text: '年龄分布图'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          bottom: '-10%',
          left: 'center'
        },
        color: ["#5470C6", "#91CC75", "#FAC858", "#EE6666", "#73C0DE", "#FFB6C1"],
        series: [
          {
            name: '年龄',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '40',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            // data: [
            //   {value: 1048, name: '搜索引擎'},
            //   {value: 735, name: '直接访问'},
            //   {value: 580, name: '邮件营销'},
            //   {value: 484, name: '联盟广告'},
            //   {value: 300, name: '视频广告'}
            // ]
            data: data.data
          }
        ]
      };

      option && agePie.setOption(option);
    },
    drawRuleBarChart(data) {
      let ruleBar = this.$echarts.init(this.$refs.ruleBar);
      this.ruleBar = ruleBar;
      let option;

      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {},
        title: {
          text: '规则分布图'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: data.labels
          }
        ],
        yAxis: [
          {
            name: "人数",
            type: 'value'
          }
        ],
        series: [
          // {
          //   name: '直接访问',
          //   type: 'bar',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [320, 332, 301, 334, 390, 330, 320]
          // },
          // {
          //   name: '异常人数',
          //   type: 'bar',
          //   stack: '广告',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [120, 132, 101, 134, 90, 230, 210]
          // },
          // {
          //   name: '联盟广告',
          //   type: 'bar',
          //   stack: '广告',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [220, 182, 191, 234, 290, 330, 310]
          // },
          // {
          //   name: '视频广告',
          //   type: 'bar',
          //   stack: '广告',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [150, 232, 201, 154, 190, 330, 410]
          // },
          // {
          //   name: '搜索引擎',
          //   type: 'bar',
          //   data: [862, 1018, 964, 1026, 1679, 1600, 1570],
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   markLine: {
          //     lineStyle: {
          //       type: 'dashed'
          //     },
          //     data: [
          //       [{type: 'min'}, {type: 'max'}]
          //     ]
          //   }
          // },
          // {
          //   name: '百度',
          //   type: 'bar',
          //   barWidth: 5,
          //   stack: '搜索引擎',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [620, 732, 701, 734, 1090, 1130, 1120]
          // },
          // {
          //   name: '谷歌',
          //   type: 'bar',
          //   stack: '搜索引擎',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [120, 132, 101, 134, 290, 230, 220]
          // },
          // {
          //   name: '必应',
          //   type: 'bar',
          //   stack: '搜索引擎',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [60, 72, 71, 74, 190, 130, 110]
          // },
          // {
          //   name: '其他',
          //   type: 'bar',
          //   stack: '搜索引擎',
          //   emphasis: {
          //     focus: 'series'
          //   },
          //   data: [62, 82, 91, 84, 109, 110, 120]
          // }
          {
            name: '测试人数',
            type: 'bar',
            data: data.data
          },

        ]
      };

      option && ruleBar.setOption(option);

    },

    // --------------------改-------------------------

    provinceInput() {
      this.selectedCity = '';
      this.selectedSchool = "";
      this.selectedGrade = "";
      this.selectedClass = "";
      this.cities = [];
      this.schools = [];
      this.grades = [];
      this.classes = [];
      if (this.selectedProvince) {
        this.fetchCityList(this.selectedProvince);

      }
      if (this.selectedProvince) {
        this.fetchSchoolProId(this.selectedProvince, this.consumeType);
      }
    },
    // 查城市列表
    fetchCityList(proId) {
      getCityInfo({
        id: proId || null,
      }).then(res => {
        // console.log(res);
        let list = res.data.data;
        this.cities = list;
      })
    },
    // 根据省份的id查询本省的学校
    fetchSchoolProId(id, type) {
      getSchoolInfo({
        provinceId: id || null,
        type,
      }).then(res => {
        let list = res.data.data;
        // console.log(list);
        this.schools = list;
      })
    },
    // 城市输入
    cityInput() {
      this.selectedSchool = "";
      this.selectedGrade = "";
      this.selectedClass = "";
      this.schools = [];
      this.grades = [];
      this.classes = [];

      if (this.selectedCity) {
        this.getSchoolList(this.selectedCity, this.consumeType);
      }

    },

    // 根据城市id查询学校
    getSchoolList(cityid, type) {
      getSchoolInfoCity({
        cityId: cityid || null,
        type,
      }).then(res => {
        let list = res.data.data;
        this.schools = list;
      })
    },

    schoolInput() { // 学校输入
      this.resetData();
      this.selectedGrade = "";
      this.selectedClass = "";
      this.grades = [];
      this.classes = [];
      if (this.selectedSchool) {
        this.fetchSchoolList(this.selectedSchool, null)
      }
    },
    fetchMentalStatistics() { // 查询心理统计数据
      NProgress.start();
      this.isSearching = true;
      let type = 1;
      if (!this.selectedGrade) {
        type = 1;
      } else if (this.selectedGrade && !this.selectedClass) {
        type = 2;
      } else if (this.selectedGrade && this.selectedClass) {
        type = 3;
      }
      mentalStatistics({
        type,
        statisticName: this.selectedSchool || null,
        gradeName: this.selectedGrade || null,
        className: this.selectedClass || null,
        startDate: this.dateArr ? this.dateArr[0] || null : null,
        endDate: this.dateArr ? this.dateArr[1] || null : null
      })
        .then(res => {
          if (res.data.code === 1) {
            let r = res.data.data;
            // console.log('==========')
            // console.log(res)
            try {
              if (!r) {
                this.$message.error('暂无统计数据');
                this.isSearching = false;
                return NProgress.done()
              }
              ;
              this.dealStatisticsData(r)
            } catch (e) {
              console.log(e)
            }
          } else {
            this.$message.success(res.data.msg || "服务异常1445!");
          }
          ;
          this.isSearching = false;
          NProgress.done();
        })
        .catch(e => {
          console.log(e)
          this.isSearching = false;
          NProgress.done();
          this.$message.error("服务异常1453!");
        });
    },
    dealStatisticsData(r) { // 处理统计数据
      this.totalNum = r.schoolNumber;
      this.mentalTestNum = r.psychologyNumber;
      this.mentalPeopleNum = r.memberNumber;
      this.badNum = r.anomalyNumber;
      let mTestNumList = mapStr2Json(r.headlineMemberNumber).filter(item => isNaN(item.label));
      if (mTestNumList.length) {
        this.hasChart = true
      }
      ;
      let mPeopleNumList = mapStr2Json(r.headlineNumber);
      let mBadNumList = mapStr2Json(r.headlineAnomalyNumber);
      let ageRate = mapStr2Json(r.ageProportion);
      this.psychologyNumber = r.psychologyNumber;
      this.resultRate = mapStr2Json(r.resultProportion);
      let ruleRate = mapStr2Json(r.ruleProportion);
      this.studentNumber = r.schoolNumber;
      let genderRate = mapStr2Json(r.sexProportion);
      if (genderRate.length) {
        this.hasGender = true
      }
      ;
      if (ageRate.length) {
        this.hasAge = true
      }
      ;
      if (ruleRate.length) {
        this.hasRule = true
      }

      let mLabels = []; // 心理测试题目
      let datasets = [Array(mTestNumList.length).fill(0), Array(mTestNumList.length).fill(0), Array(mTestNumList.length).fill(0)]; // 心理测试数据
      let ageData = { // 年龄分布
        labels: [],
        data: []
      };
      let genderData = { // 性别分布
        data: []
      };
      let ruleData = { // 规则数据
        labels: [],
        data: []
      };

      // 处理心理测试数据
      for (let a = 0; a < mTestNumList.length; a++) {
        let chartName = mTestNumList[a].label;
        datasets[0][a] = mTestNumList[a].rate; // 回答次数
        mLabels.push(chartName);

        for (let b = 0; b < mPeopleNumList.length; b++) {
          if (mPeopleNumList[b].label === chartName) {
            datasets[1][a] = mPeopleNumList[b].rate; // 回答人数
            continue
          }
        }
        ;

        for (let c = 0; c < mBadNumList.length; c++) {
          if (mBadNumList[c].label === chartName) {
            datasets[2][a] = mBadNumList[c].rate; // 异常人数
            continue
          }
        }
      }
      ;

      // 处理性别数据
      for (let d = 0; d < genderRate.length; d++) {
        if (genderRate[d].label == '1') {
          genderData.data[0] = {name: '男生', value: genderRate[d].rate}
        } else if (genderRate[d].label == '2') {
          genderData.data[1] = {name: '女生', value: genderRate[d].rate}
        }
      }
      ;

      // 年龄数据
      for (let e = 0; e < ageRate.length; e++) {
        ageData.labels.push(ageRate[e].label + '岁');
        ageData.data.push({
          name: ageRate[e].label + '岁',
          value: ageRate[e].rate
        })
      }
      ;

      // 规则数据
      for (let i = 0; i < ruleRate.length; i++) {
        if (isNaN(ruleRate[i].label)) {
          ruleData.labels.push(ruleRate[i].label);
          ruleData.data.push({
            name: ruleRate[i].label,
            value: ruleRate[i].rate
          })
        }
      }
      ;
      this.testChartData = { // 测试分布数据
        labels: mLabels,
        data: datasets
      };
      this.genderChartData = genderData.data;
      this.ageChartData = ageData;
      this.ruleChartData = ruleData;

      let {labels, data} = this.testChartData;
      try {
        // 心理测试分布图
        this.drawChartLineChart(labels, data[0], data[1], data[2]);
        this.chartLineChart.resize();
        // 性别分布图
        this.drawGenderPieChart(this.genderChartData);
        this.genderPie.resize();
        // 年龄分布图
        this.drawAgePieChart(this.ageChartData);
        this.agePie.resize();
        // 规则分布
        this.drawRuleBarChart(this.ruleChartData);
        this.ruleBar.resize();
      } catch (e) {
        console.warn(e)
      }

    },
    gradeInput(item) { // 年级输入
      console.log("选中年级： " + item)
      this.resetData();
      this.selectedClass = "";
      this.classes = [];
      // if (this.selectedGrade) {
      //   this.fetchSchoolList(this.selectedSchool, this.selectedGrade);
      // }
      if (item) {
        this.fetchSchoolList(this.selectedSchool, item);
      }
    },
    classInput(item) { // 班级输入
      console.log('班级====' + item);
      this.resetData();
    },
    fetchAllSchool() { // 获取学校信息
      this.schoolLoading = true;
      getMentalSchool()
        .then(res => {
          console.log("school======")
          console.log(res)
          this.schoolLoading = false;
          if (res.data.code === 1) {
            let list = res.data.data || [];
            this.schools = list.map(item => item.schoolTitle)
          } else {
            this.$message.error(res.data.msg || "网络异常!");
          }
        })
        .catch(e => {
          this.schoolLoading = false;
          this.$message.error("网络异常!");
        });
    },
    fetchGrade(schoolName) { // 获取年级
      this.gradeLoading = true;
      getMentalGrade(schoolName)
        .then(res => {
          this.gradeLoading = false;
          if (res.data.code === 1) {
            this.grades = res.data.data || [];
          } else {
            this.$message.error(res.data.msg || "网络异常!");
          }
        })
        .catch(e => {
          this.gradeLoading = false;
          this.$message.error("网络异常!");
        });
    },
    fetchClass(schoolName, gradeName) { // 获取班级
      this.classLoading = true;
      getMentalClass(schoolName, gradeName)
        .then(res => {
          this.classLoading = false;
          if (res.data.code === 1) {
            this.classes = res.data.data || [];
          } else {
            this.$message.error(res.data.msg || "网络异常!");
          }
        })
        .catch(e => {
          this.classLoading = false;
          this.$message.error("网络异常!");
        });
    },
    resetData() {
    },
    getWidth(name) { // 获取指定元素的宽度
      // return this.$refs[name].getBoundingClientRect().width;
    },
    fetchSchoolList(enterpriseName, grade) { // 查询学校列表
      getSchoolInfo({
        enterpriseName: enterpriseName || null,
        grade: grade || null,
        grades: null,
        type: this.consumeType
      })
        .then(res => {
          console.log(res);
          let list = res.data.data || [];
          list = list.filter(item => item);
          if (!enterpriseName) { // 查询所有学校
            this.schools = list
          } else if (enterpriseName && !grade) { // 查询年级
            this.grades = list
          } else if (enterpriseName && grade) { // 查询班级
            this.classes = list
          }
        })
        .catch(e => {

        })
    },
    fetchSchoolMembers(index) { // 获取学校成员
      this.memberLoading = true;
      getSchoolMember({
        index,
        count: this.pageSize,
        queryParam: {
          enterpriseName: this.selectedSchool || null,
          grade: this.selectedGrade || null,
          grades: this.selectedClass
        }
      })
        .then(res => {
          this.memberLoading = false;
          let list = res.data.data.list || [];
          list.forEach(item => {
            if (item.createDate) {
              item.createDate = formatDate(item.createDate, 'zh:')
            }
          });
          this.memberTotal = res.data.data.totalRecord;
          this.memberList = list;
          console.log(list)

        })
        .catch(e => {
          this.memberLoading = false
        })
    },
    formatItemData(list) { // 格式化统计信息
      const tempList = [];
      const tempObj = {};
      list.forEach(item => {
        if (!tempObj[item.name]) {
          tempObj[item.name] = [item.fitbarOpenId];
          tempList.push(item)
        } else {
          if (!tempObj[item.name].includes(item.fitbarOpenId)) {
            tempObj[item.name].push(item.fitbarOpenId);
            tempList.push(item)
          }
        }
      });
      return {
        girl: tempList.filter(item => item.gender == '女').length,
        boy: tempList.filter(item => item.gender == '男').length
      }
    },
    watchSize() { // 图表重置尺寸
      this.chartLineChart.resize();
      this.genderPie.resize();
      this.agePie.resize();
      this.ruleBar.resize()
    },
    goExportResult(row) { // 查看结果报表
      this.$router.push({
        path: `/statistics/mental/report/${row.memberId}/${row.listId}/${row.chartName}/${row.testTime}`,
      })
    },
    beginSearchNumber() { // 查询统计人数
      if (!this.selectedSchool) return;
      this.fetchAllMember()
    },
    fetchAllMember() { // 查询学校所有成员
      this.searchLoading = true;
      getMemberBySchool(this.selectedSchool)
        .then(res => {
          this.searchLoading = false;
          const list = res.data.data || [];
          this.formatMemberByGrade(list)
          console.log(list)
        })
        .catch(e => {
          this.searchLoading = false
        })
    },
    formatMemberByGrade(list) { // 根据年级区分学校
      const gradeObj = {};
      const tempList = [];
      const classList = [];
      let num = 0;
      list.forEach(item => {
        const gradeKey = item.grade ? item.grade : '未知年级';
        if (!gradeObj[gradeKey]) {
          gradeObj[gradeKey] = [item]
        } else {
          gradeObj[gradeKey].push(item)
        }
      });
      for (let key in gradeObj) {
        let tempObj = {};
        tempObj.gradeName = key;
        tempObj.total = gradeObj[key].length;
        num += gradeObj[key].length;
        gradeObj[key].forEach(item => {
          const classKey = item.grades ? (+item.grades.slice(0, item.grades.length - 1) + '班') : '未知班级';
          if (item.grades && !classList.includes(+item.grades.slice(0, item.grades.length - 1))) {
            classList.push(+item.grades.slice(0, item.grades.length - 1))
          }
          ;
          if (!tempObj[classKey]) {
            tempObj[classKey] = [item]
          } else {
            tempObj[classKey].push(item)
          }
        });
        tempList.push(tempObj)
      }
      ;
      tempList.sort((a, b) => this.gradeMap[a.gradeName] - this.gradeMap[b.gradeName]);
      this.classMaxNum = Math.max.apply(null, classList);
      this.gradeNumList = tempList;
      this.memberTotalNum = num
    },

    //  --------------------myself--------------------
    //计算参与人数占比mentalPeopleNum totalNum
    joinPerson() {
      return parseInt((this.mentalPeopleNum / this.totalNum) * 100)
      // return 10
    },
    //计算badnum
    badPerson() {
      return parseInt((this.badNum / this.totalNum) * 100)
    },
    //  查看表单
    lookFirm() {
      // alert(123)
      this.index = 3
      if (!this.selectedSchool) return;
      this.fetchAllMember()
    },
    //  计算点击事件
    clickIndex(index) {
      let {labels, data} = this.testChartData;
      // console.log("===" + data[0])
      // console.log("=====" + labels)
      if (this.index == 3 || index == 3) index = 2
      this.index = index == 1 ? 2 : 1;
      console.log(" ------ ------- ")
      console.log("计算后==" + index)
      let that = this;
      if (index == 2) {
        setTimeout(function () {
          try {
            // 心理测试分布图
            that.drawChartLineChart(labels, data[0], data[1], data[2]);
            // 性别分布图
            that.drawGenderPieChart(that.genderChartData);
            // 年龄分布图
            that.drawAgePieChart(that.ageChartData);
            // 规则分布
            that.drawRuleBarChart(that.ruleChartData)
            console.log('渲染图表')
          } catch (e) {
            console.log(e)
          }
        }, 500)

      } else if (index == 1) {
        console.log('查看成员')
      }

    },


  },
  created() {
    this.selectedSchool = this.$route.params.name

    getProvinceInfo({
      ctype: 1,
    }).then(res => {
      // console.log(res);
      let list = res.data.data;
      this.provinces = list;
    })
    this.fetchMentalStatistics();
    // this.fetchNameList();
    this.fetchBadNum(1);
    this.fetchSchoolMembers(1)


  },
  mounted() {
    // this.chartLineWidth = this.getWidth("chartLineOuter") - 30;
    // this.genderPieWidth = this.getWidth('genderPieWrap') - 30;
    // this.agePieWidth = this.getWidth('agePieWrap') - 30;
    // this.ruleBarWidth = this.getWidth('ruleBarWrap') - 30;

    let roleId = sessionStorage.getItem("role");
    let roleTitle = sessionStorage.getItem('roleTitle');
    let name = sessionStorage.getItem("username");
    if (roleTitle == '学校') { // 学校
      this.consumeType = 1;
      this.canSelect = true;
      this.selectedSchool = name;
      this.fetchSchoolList(this.selectedSchool, null)
    } else if (roleTitle == '公司') { // 公司
      this.consumeType = 2;
      this.canSelect = true;
      this.selectedSchool = name
    } else {
      this.fetchSchoolList(this.selectedSchool, null);
    }
    ;

    const _this = this;
    let fn = this.watchSize.bind(_this);
    window.onresize = () => {
      fn();
    };
  }
};
</script>

<style lang="scss">
//<style lang="scss" scoped>

.grade-data {
  // display: flex;
  margin: 20px auto 0;
  border-left: 1px solid #ccc;
  border-top: 1px solid #ccc;
  box-sizing: border-box;

  .s-name {
    padding: 15px 0;
    text-align: center;
    background-color: #F0F0F0;
    font-weight: bold;
    border: 1px solid #F0F0F0;
    font-size: 22px;
  }

  .class-name {
    //班级列表 1234567班的班
    border-right: 1px solid #746b6b;


    span {
      display: flex;
      border-bottom: 1px solid #847f7f;
      width: 60px;
      height: 60px;
      //background: #ffffff;
    }
  }

  span {
    display: block;
    width: 100px;
    height: 60px;
    line-height: 40px;
    text-align: center;
    box-sizing: border-box;
    //background: #ffffff;
  }

  .grade-list {
    & > div {
      display: flex;

      div {
        border-right: 1px solid #ccc;
        box-sizing: border-box;
        transition: .4s;

        &:hover {
          background-color: #f8f8f8;
        }
      }
    }

    span {
      border-bottom: 1px solid #ccc;
      box-sizing: border-box;
    }
  }
}

.cell {
  white-space: pre-line !important;
}

.mental-statistics {

  padding: 14px 92px 40px 92px;

  h2 {
    margin-bottom: 28px;
  }

  .heart_search1 {
    padding-right: 17px;
    border-radius: 20px;
    box-shadow: 0px 0px 20px rgba(109, 193, 150, 0.3);
    height: 68px;
    line-height: 68px;
    white-space: nowrap;
    display: flex;
    justify-content: start;
    align-items: center;
    margin-top: 28px;

    .el-range-editor--mini.el-input__inner {
      //这是时间选择器
      //margin-top: 19px;
    }

    .el-range-editor.el-input__inner {
      //应该是后面的年级和班级的
      width: 250px;
    }

    .el-input--mini .el-input__inner {
      width: 132px;
      padding: 0;
    }

    span {
      padding: 0 5px 0 25px;
    }
  }

  .bread_crumbs {
    display: flex;
    justify-content: space-between;
    border-bottom: 2px solid #E7E7E7 !important;

    .bread {

    }

    .view_switch {
      margin-top: 30px;
      width: 96px;
      height: 32px;
      border-radius: 16px;

      button {
        border: none;
        outline: none;
        width: 96px;
        height: 32px;
        border-radius: 16px;
        background: rgba(171, 195, 182, 0.14);
        opacity: 1;
      }

    }

    .view_switch:hover {
      background: #6AE0B1;
    }
  }

  //---------------------------------------------------
  .head-box {
    padding-bottom: 20px;

    div {
      margin: 0 20px;

      span:nth-of-type(1) {
        color: #242424;
        font-size: 20px;
        font-weight: bold;
      }

      span:nth-of-type(2) {
        color: #4ac493;
        font-weight: bold;
        font-size: 28px;
      }
    }
  }

  .filter-wrap {
    display: flex;
    align-items: flex-end;
    flex-direction: column;
  }

  .table-item {
    display: flex;

    .t-title {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 10px;
      font-weight: bold;
      font-size: 20px;
      width: 200px;
      border: 1px solid #EBEEF5;
      border-right: none;
    }
  }

  .no-mental {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 300px;

    span {
      padding-top: 10px;
      color: #666;
      font-size: 12px;
    }
  }

  .p-wrap {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
  }

  .p-innter {
    width: calc((100% - 40px) / 3);
    background-color: #ffffff;
    border-radius: 4px;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    padding: 15px;
  }

  .chart-info-out {
    background-color: #ffffff;
    margin-top: 20px;
    border-radius: 4px;
    padding: 15px;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);

    .chart-info {
      height: 300px;

      & > div {
        width: 100% !important;
      }

      canvas {
        width: 100% !important;
      }
    }
  }

  .c-head {
    display: flex;
    justify-content: space-between;
  }

  .h-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 266px;
    height: 108px;
    background-color: #ffffff;
    border-radius: 4px;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    padding: 0 15px;

    .h-left {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80px;
      height: 80px;
      border-radius: 4px;
      background-color: #ffffff;
      transition: all 0.4s;

      background-size: 60px 60px;
      background-position: center center;
      background-repeat: no-repeat;
    }

    .h-right {
      div:nth-of-type(1) {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
      }

      div:nth-of-type(2) {
        font-size: 20px;
        color: #666;
      }
    }
  }

  .total-num .h-left {
    background-image: url("../assets/images/user_blank.png");
  }

  .mental_num .h-left {
    background-image: url("../assets/images/mental_num.png");
  }

  .person-num .h-left {
    background-image: url("../assets/images/person_num.png");
  }

  .bad-num .h-left {
    background-image: url("../assets/images/bad_num.png");
  }

  .total-num:hover {
    .h-left {
      background-image: url("../assets/images/user_hover.png");
      background-color: #40c9c6;
    }
  }

  .mental_num:hover {
    .h-left {
      background-image: url("../assets/images/mental_num_hover.png");
      background-color: #36a3f7;
    }
  }

  .person-num:hover {
    .h-left {
      background-image: url("../assets/images/person_num_hover.png");
      background-color: #34bfa3;
    }
  }

  .bad-num:hover {
    .h-left {
      background-image: url("../assets/images/bad_num_hover.png");
      background-color: #f4516c;
    }
  }

  .chart-outter {
    margin-top: 20px;
    padding: 20px;
    background-color: #f0f2f5;
  }

  .gender-pic {
    display: flex;
    justify-content: space-between;
  }

  .bar-wrapper {
    & > div {
      width: 50%;
      float: left;
    }
  }

  .bar-wrap {
    // display: flex;
    & > div {
      // width: 50%;
      // width: calc((100% - 10px) / 2);
      // height: 500px;
      // &:nth-of-type(1) {
      //   margin-right: 10px;
      // }
    }
  }

  .split-line {
    margin-top: 40px;
    position: relative;
    height: 2px;
    background-color: #4ac493;

    div {
      padding: 0 10px;
      position: absolute;
      display: inline-block;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      background-color: #ffffff;
      z-index: 3;

      span {
        color: #4ac493;
        font-size: 20px;
        font-weight: bold;
      }
    }
  }
}

.bread-crumbs {
  display: flex;
  justify-content: space-between;
  border-bottom: 2px solid #E7E7E7;

  .bread {

  }

  .view_switch {
    margin-top: 30px;
    width: 96px;
    height: 32px;
    border-radius: 16px;

    button {
      border: none;
      outline: none;
      width: 96px;
      height: 32px;
      border-radius: 16px;
      background: rgba(171, 195, 182, 0.14);
      opacity: 1;
    }

  }

  .view_switch:hover {
    background: #6AE0B1;
  }
}

.heart_block1 {
  display: flex;
  margin-top: 28px;

  .block1_pic {
    padding: 19px 40px 19px 40px;
    //width: 292px;
    flex: 1;
    height: 161px;
    //border: 1px solid #000;
    border-radius: 20px;
    box-shadow: 0px 0px 6px rgba(109, 193, 150, 0.3);

    .personIn{
      //参与人数占比那行字
      margin-bottom: 4px;
      font-weight: 100;
    }

    .el-icon-arrow-down:before {
      content: '' !important;
    }

    .left {
      width: 25%;
      margin-top: 25px;
      display: inline-block;
      // float: left;

      .bad_num {//小标题
        // width: 80px;
        // font-size: 16px;
        font-family: PingFang SC;
        line-height: 22px;
        color: #B2B2B9;
        white-space: nowrap;
        opacity: 1;
        cursor: pointer;
      }
      .big_badNum{
        //数字
        font-weight: bolder;
        font-size: 25px;
      }

    }

    .right {
      width: 75%;
      margin-top: 20px;
      float: right;
      text-align: center;
      display: inline-block;

    }

    //单独控制的类
    .bad_num1{
      margin-top: 20px;
      font-family: PingFang SC;
      line-height: 22px;
      color: #B2B2B9;
      white-space: nowrap;
      opacity: 1;
      cursor: pointer;
    }
    .big_badNum1{
      margin-bottom: 10px;
      font-weight: bolder;
      font-size: 25px;
    }
    .beginSearchNumber {//查看参与人数的文字
      //padding: 0;
      cursor: pointer;
      text-align: center;
      white-space: nowrap;
      line-height: 121px;

    }

  }

  .block1_pic:nth-of-type(5) {
    width: 186px;
  }

  .block1_pic:hover {
    background-image: linear-gradient(to right, #4EC797, #6AE0B1);

    p {
      color: white !important;
    }
  }
}

#heart_block2 {
  //width: 1486px;
  height: 456px;
  display: flex;
  margin-top: 42px;
  padding: 10px;
  border-radius: 20px;
  box-shadow: 0px 0px 20px rgba(109, 193, 150, 0.3);
  //background-color: #6AE0B1;
}

.heart_block3 {
  margin-top: 62px;
  //width: 100%;
  display: flex;
  vertical-align: center;
  align-items: center;

  .block3_pic1 {
    text-align: center;
    align-items: center;
    padding: 15px;
    border-radius: 20px;
    box-shadow: 0px 0px 20px rgba(109, 193, 150, 0.3);
    display: inline-block;
    //width: 425px;
    flex: 1;
    //height: 434px;
    //background: lightgreen;
  }

  .block3_pic2 {
    text-align: center;
    padding: 15px;
    flex: 1;

    border-radius: 20px;
    box-shadow: 0px 0px 20px rgba(109, 193, 150, 0.3);
    margin: 0 20px 0 20px;
    //width: 425px;
    display: inline-block;
    //height: 434px;
    //background-color: lightpink;
  }

  .block3_pic3 {
    text-align: center;
    padding: 15px;
    flex: 1;
    border-radius: 20px;
    box-shadow: 0px 0px 20px rgba(109, 193, 150, 0.3);
    display: inline-block;
    //width: 596px;
    //height: 434px;
    //background-color: lightblue;
  }
}

//一堆选择框按钮
.choose_content {

  margin-top: 14px;
  //padding-left: 30px;;
  margin-bottom: 14px;
  height: 244px;
  background: #ffffff;
  border: 1px solid #efefef;
  border-radius: 16px;
  box-shadow: 0px 0px 20px rgba(109, 193, 150, 0.3);
  white-space: nowrap;
  user-select: none;


  .choose_person {
    display: flex;
    justify-content: start;
    line-height: 69px;
    border-bottom: 1px dashed #F2F2F2;
    outline: none;

    span {
      //类型的文字 tmd也包括按钮 草了
      margin: 0;
      border: none !important;
      border-radius: 16px !important;
    }

    .person_button {
      background: #ffffff;
      height: 69px;
      display: flex;
      justify-content: start;
      align-items: center;
      border-radius: 16px;

    }

  }

  .choose_grade {
    display: flex;
    outline: none;
    justify-content: start;
    line-height: 50px;
    white-space: nowrap;
    //选择年级

    span {
      //类型的文字 tmd也包括按钮 草了
      margin: 0;
      border: none !important;
      border-radius: 16px !important;
    }

    .grade_button {
      //按钮组
      background: #ffffff;
      height: 50px;

    }
  }

  .choose_class {
    //选择班级
    display: flex;
    outline: none;
    justify-content: start;
    line-height: 50px;
    white-space: nowrap;

    span {
      //类型的文字 tmd也包括按钮 草了
      margin: 0;
      border: none !important;
      border-radius: 16px !important;
    }

    .class_button {
      //按钮组
      background: #FBFBFB;
      height: 50px;

    }
  }

  .choose_test {
    //选择表
    outline: none;
    display: flex;
    justify-content: start;
    line-height: 69px;
    white-space: nowrap;
    padding-left: 40px;

    span {
      //类型的文字 tmd也包括按钮 草了
      margin: 0;
      border: none !important;
      border-radius: 16px !important;
    }

    .test_button {
      //按钮组
      //background: #FBFBFB;
      height: 69px;
      border: none;
      background: none;

    }
  }

  //因为span文字被button占用了 所以给span文字加一个类
  .choose_text {
    margin: 0 40px 0 30px !important;
  }

}

//列表样式
.table_list {
  background: #ffffff;
  border-radius: 10px;
  padding: 5px;
  box-shadow: 0px 0px 20px rgba(109, 193, 150, 0.3);

  .table_button {
    background: none;
    height: 34px;
    font-size: 14px;
    color: #ABC3B6;
    border-radius: 8px;

  }

  .table_button:hover {
    background: #B0C2B7;
    color: white;
  }
}

</style>
